package com.ayu.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ayu.shortlink.admin.common.biz.user.UserContext;
import com.ayu.shortlink.admin.common.constant.RedisCacheConstant;
import com.ayu.shortlink.admin.common.convention.exception.ClientException;
import com.ayu.shortlink.admin.common.convention.exception.ServiceException;
import com.ayu.shortlink.admin.common.convention.result.Result;
import com.ayu.shortlink.admin.dao.entity.GroupDO;
import com.ayu.shortlink.admin.dao.entity.GroupUniqueDO;
import com.ayu.shortlink.admin.dao.mapper.GroupMapper;
import com.ayu.shortlink.admin.dao.mapper.GroupUniqueMapper;
import com.ayu.shortlink.admin.dto.req.ShortLinkGroupAddReqDTO;
import com.ayu.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.ayu.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.ayu.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import com.ayu.shortlink.admin.remote.dto.ShortLinkActualRemoteService;
import com.ayu.shortlink.admin.remote.dto.resp.ShortLinkGroupCountRespDTO;
import com.ayu.shortlink.admin.service.GroupService;
import com.ayu.shortlink.admin.util.RandomCodeGenerator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
@Slf4j
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {
    private final RedissonClient redissonClient;
    private final ShortLinkActualRemoteService shortLinkActualRemoteService;
    private final RBloomFilter<String> gidRegisterCachePenetrationBloomFilter;
    private final GroupUniqueMapper groupUniqueMapper;
    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;

    @Override
    public void addGroup(ShortLinkGroupAddReqDTO requestPram) {
        addGroup(UserContext.getUsername(),requestPram);
    }

    @Override
    public void addGroup(String username, ShortLinkGroupAddReqDTO requestPram) {
        RLock lock = redissonClient.getLock(String.format(RedisCacheConstant.LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try {
            //查看是否还能添加分组
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, username)
                    .eq(GroupDO::getDelFlag, 0);
            List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
            if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() == groupMaxNum) {
                throw new ClientException(String.format("已超出最大分组数：%d", groupMaxNum));
            }

            int retryCount = 0;
            int maxRetries = 10;
            String gid = null;
            while (retryCount < maxRetries) {
                gid = saveGroupUniqueReturnGid();
                if (StrUtil.isNotEmpty(gid)) {
                    GroupDO groupDO = GroupDO.builder()
                            .gid(gid)
                            .sortOrder(0)
                            .username(username)
                            .name(requestPram.getName())
                            .build();
                    baseMapper.insert(groupDO);
                    gidRegisterCachePenetrationBloomFilter.add(gid);
                    break;
                }
                retryCount++;
            }
            if (StrUtil.isEmpty(gid)) {
                throw new ServiceException("生成分组标识频繁");
            }
        }finally {
            lock.unlock();
        }

    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        List<GroupDO> list = lambdaQuery()
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder)
                .list();
        Result<List<ShortLinkGroupCountRespDTO>> listResult =
                shortLinkActualRemoteService.listGroupShortLinkCount(list.stream().map(GroupDO::getGid).toList());

        List<ShortLinkGroupRespDTO> linkGroupRespDTOS =
                BeanUtil.copyToList(list, ShortLinkGroupRespDTO.class);

        linkGroupRespDTOS.forEach(each -> {
            Optional<ShortLinkGroupCountRespDTO> first = listResult.getData().stream().filter(item -> {
                return Objects.equals(item.getGid(), each.getGid());
            }).findFirst();

            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return linkGroupRespDTOS;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        lambdaUpdate()
                .eq(GroupDO::getGid,requestParam.getGid())
                .eq(GroupDO::getUsername,UserContext.getUsername())
                .eq(GroupDO::getDelFlag,0)
                .set(GroupDO::getName,requestParam.getName());

    }

    @Override
    public void deleteGroup(String gid) {
        GroupDO groupDO = lambdaQuery()
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0)
                .one();
        groupDO.setDelFlag(1);
        baseMapper.updateById(groupDO);
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestPram) {
        requestPram.forEach(item -> {
            GroupDO groupDO = lambdaQuery()
                    .eq(GroupDO::getDelFlag, 0)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, item.getGid())
                    .one();
            if(groupDO != null){
                groupDO.setSortOrder(item.getSortOrder());
                baseMapper.updateById(groupDO);
            }
        });
    }

    private String saveGroupUniqueReturnGid() {
        String gid = RandomCodeGenerator.generateCode();
        if (!gidRegisterCachePenetrationBloomFilter.contains(gid)) {
            GroupUniqueDO groupUniqueDO = GroupUniqueDO.builder()
                    .gid(gid)
                    .build();
            try {
                groupUniqueMapper.insert(groupUniqueDO);
            } catch (DuplicateKeyException e) {
                return null;
            }
        }
        return gid;
    }
}
